# coding: UTF-8
# Filename : Factory.py
# Company : imedia
# -*-coding:utf-8 -*-

'''
API代码生成器
@author: rose
'''
import os, for_element

class Factory:
    def __init__(self, table, columns):
        self.table = table
        self.columns = columns
    
    def setTable(self, table):
        self.table = table
    
    def getTable(self):
        return self.table
    
    def setColumns(self, columns):
        self.columns = columns
    
    def getColumns(self):
        return self.columns
    
    def create(self):
         #循环获取动态数据
         body_template_middle_str = ''
         xml_model_body_str = ''
         if isinstance(self.columns, list):
             count = 0
             for column in self.columns:
                 body_template_middle_str += for_element.body_template_middle.replace('${column}', column).replace('${count}', str(count))
                 xml_model_body_str += for_element.xml_model_body.replace('${column}', column)
                 count += 1
             
             api_model_str = self.getFileModel('api.tmp')
             date_model_str = self.getFileModel('data_model.tmp')
             
             #创建模板py
             date_model_str = date_model_str.replace('${xml_model_body}', xml_model_body_str)
             date_model_str = date_model_str.replace('${table}', self.table)
             self.writePy('data_model', date_model_str)
             
             #创建接口py
             columns_str = ', '.join(self.columns)
             api_model_str = api_model_str.replace('${table}', self.table)
             api_model_str = api_model_str.replace('${columns}', columns_str)
             api_model_str =  api_model_str.replace('${body_template_middle}', body_template_middle_str)
             self.writePy('api', api_model_str)
             
             #创建url信息
             self.createUrlPatterns()
    #读取文件内容    
    def getFileModel(self, filename):
        f = file(filename)
        f.encoding
        rst_str = ''
        for l in f:
            rst_str += str(l)
        return rst_str
    
    #写入数据到指定文件
    def writePy(self, api_flag, str):
        self.writeToDisk(self.table + os.sep + self.table + '_'+ api_flag +'.py', str)
    
    #写入数据到某文件
    def writeToDisk(self, filename, str):
        if not os.path.exists(self.table):
            os.mkdir(self.table)
        f = file(filename, 'w')
        f.write(str)
        f.close()
    #生成url配置信息
    def  createUrlPatterns(self):
        '''goods_detail'''
        '''goods_list'''
        model_list = '''
urlpatterns = patterns('api',
(r'^app/${table}/list', '${table}.${table}_api.${table}_list'),
(r'^app/${table}/', '${table}.${table}_api.${table}_detail'),
)
'''
        url_str = model_list.replace('${table}', self.table)
        self.writeToDisk(self.table + os.sep + 'url.txt', url_str)
        
        
